<template>
  <div class="register-page min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4">
    <div class="max-w-md w-full">
      <!-- Logo -->
      <div class="text-center mb-8">
        <NuxtLink to="/" class="inline-flex items-center space-x-2">
          <div class="i-mdi-code-braces text-5xl text-primary-600" />
          <span class="text-3xl font-bold">代码小库</span>
        </NuxtLink>
        <p class="mt-2 text-gray-600">创建您的账户</p>
      </div>

      <!-- 注册表单 -->
      <div class="card">
        <form @submit.prevent="handleRegister">
          <!-- 用户名 -->
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-2">
              用户名
            </label>
            <input
              v-model="form.username"
              type="text"
              placeholder="请输入用户名"
              class="input w-full"
              :class="{ 'border-red-500': errors.username }"
              @blur="validateUsername"
            />
            <p v-if="errors.username" class="text-red-500 text-sm mt-1">
              {{ errors.username }}
            </p>
          </div>

          <!-- 邮箱 -->
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-2">
              邮箱
            </label>
            <input
              v-model="form.email"
              type="email"
              placeholder="请输入邮箱"
              class="input w-full"
              :class="{ 'border-red-500': errors.email }"
              @blur="validateEmail"
            />
            <p v-if="errors.email" class="text-red-500 text-sm mt-1">
              {{ errors.email }}
            </p>
          </div>

          <!-- 密码 -->
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-2">
              密码
            </label>
            <input
              v-model="form.password"
              type="password"
              placeholder="请输入密码（6-20位）"
              class="input w-full"
              :class="{ 'border-red-500': errors.password }"
              @blur="validatePassword"
            />
            <p v-if="errors.password" class="text-red-500 text-sm mt-1">
              {{ errors.password }}
            </p>
          </div>

          <!-- 确认密码 -->
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-2">
              确认密码
            </label>
            <input
              v-model="form.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              class="input w-full"
              :class="{ 'border-red-500': errors.confirmPassword }"
              @blur="validateConfirmPassword"
            />
            <p v-if="errors.confirmPassword" class="text-red-500 text-sm mt-1">
              {{ errors.confirmPassword }}
            </p>
          </div>

          <!-- 服务条款 -->
          <div class="mb-6">
            <label class="flex items-start">
              <input
                v-model="form.agree"
                type="checkbox"
                class="mt-1 mr-2"
              />
              <span class="text-sm text-gray-600">
                我已阅读并同意
                <NuxtLink to="/terms" class="text-primary-600">服务条款</NuxtLink>
                和
                <NuxtLink to="/privacy" class="text-primary-600">隐私政策</NuxtLink>
              </span>
            </label>
            <p v-if="errors.agree" class="text-red-500 text-sm mt-1">
              {{ errors.agree }}
            </p>
          </div>

          <!-- 注册按钮 -->
          <button
            type="submit"
            :disabled="loading"
            class="btn-primary w-full py-3 text-lg"
          >
            {{ loading ? '注册中...' : '注册' }}
          </button>
        </form>
      </div>

      <!-- 登录链接 -->
      <p class="mt-4 text-center text-sm text-gray-600">
        已有账户？
        <NuxtLink to="/auth/login" class="text-primary-600 hover:text-primary-700 font-medium">
          立即登录
        </NuxtLink>
      </p>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  emailRule,
  passwordRule,
  usernameRule,
  requiredRule,
  confirmPasswordRule,
} from '~/utils/validation'

definePageMeta({
  layout: 'blank',
  middleware: 'guest',
})

const router = useRouter()
const authStore = useAuthStore()

const form = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  agree: false,
})

const errors = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  agree: '',
})

const loading = ref(false)

function validateUsername() {
  const result = requiredRule(form.username)
  if (result !== true) {
    errors.username = result
    return false
  }
  const usernameResult = usernameRule(form.username)
  if (usernameResult !== true) {
    errors.username = usernameResult
    return false
  }
  errors.username = ''
  return true
}

function validateEmail() {
  const result = requiredRule(form.email)
  if (result !== true) {
    errors.email = result
    return false
  }
  const emailResult = emailRule(form.email)
  if (emailResult !== true) {
    errors.email = emailResult
    return false
  }
  errors.email = ''
  return true
}

function validatePassword() {
  const result = requiredRule(form.password)
  if (result !== true) {
    errors.password = result
    return false
  }
  const passwordResult = passwordRule(form.password)
  if (passwordResult !== true) {
    errors.password = passwordResult
    return false
  }
  errors.password = ''
  return true
}

function validateConfirmPassword() {
  const result = requiredRule(form.confirmPassword)
  if (result !== true) {
    errors.confirmPassword = result
    return false
  }
  const confirmResult = confirmPasswordRule(form.password)(form.confirmPassword)
  if (confirmResult !== true) {
    errors.confirmPassword = confirmResult
    return false
  }
  errors.confirmPassword = ''
  return true
}

async function handleRegister() {
  // 验证表单
  const usernameValid = validateUsername()
  const emailValid = validateEmail()
  const passwordValid = validatePassword()
  const confirmPasswordValid = validateConfirmPassword()
  
  if (!form.agree) {
    errors.agree = '请阅读并同意服务条款和隐私政策'
    return
  } else {
    errors.agree = ''
  }
  
  if (!usernameValid || !emailValid || !passwordValid || !confirmPasswordValid) {
    return
  }

  loading.value = true

  try {
    const result = await authStore.register(form)
    
    if (result.success) {
      router.push('/')
    } else {
      alert(result.message || '注册失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// SEO
useSeoMeta({
  title: '注册 - 代码小库',
  robots: 'noindex',
})
</script>